# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/10 18:32
@Auth ： 李天天
"""
# from logzero import logger
from Common.handle_pid import DHDevices
from solox.public.adb import adb
from solox.public.apm import AppPerformanceMonitor
from Common.connect_to_device import *
from Common.handle_log import do_log
dhd = DHDevices()



class MyAppPerformanceMonitor(AppPerformanceMonitor):
    def collectSysMemory(self):
        try:
            cmd = 'cat /proc/meminfo'
            output = adb.shell(cmd=cmd, deviceId=self.deviceId)
            mem_total = float(re.search(r'MemTotal:\s+(\d+)\s+kB', output).group(1))
            mem_free = float(re.search(r'MemAvailable:\s+(\d+)\s+kB', output).group(1))
            mem_rate = round((mem_total - mem_free) / 1024, 2)
        except Exception as e:
            mem_rate = 0
            do_log.info(e)
        return mem_rate


class HandleDevices:
    def __init__(self, pkgName):
        self.pkgName = pkgName

    def handle_main_device(self, deviceId_001):
        CPDemo_processListdic = dhd.getPidNew(deviceId=deviceId_001, pkgName=self.pkgName)
        pid_list={"u0":None,"u10":None,"u11":None}
        if len(CPDemo_processListdic)==0:
            do_log.info(f"0:无法获取到有效的进程号,包名为{package_name}")
            return None,None,None,None
        if len(CPDemo_processListdic)==1:
            do_log.info(f"1:获取到有效的进程号为1个,包名为{package_name}")
            try:
                package_name_main=CPDemo_processListdic[0]['pkgName']
                pid_main = CPDemo_processListdic[0]["PID"]
                user_main=CPDemo_processListdic[0]["USER"]
            except:
                do_log.info(f"1.尝试获取1个有效进程号失败,包名为{package_name}")
                return None, None, None, None
            do_log.info(f"1.尝试获取1个有效进程号成功,获取的进程号为{pid_main},user为{user_main}获取的包名为{package_name_main}")
            if package_name_main==package_name and pid_main:
                do_log.info(f"1.尝试获取1个有效进程号成功,获取的进程号为{pid_main}获取的包名为{package_name}")
                apm_pid_main = MyAppPerformanceMonitor(pkgName=self.pkgName, platform='Android',
                                                       deviceId=deviceId_001,
                                                       surfaceview=False,
                                                       noLog=False, pid=pid_main, record=False, collect_all=False)
                return apm_pid_main,pid_main,None,None
            else:
                do_log.info(f"1.尝试获取1个有效进程号失败,获取的进程号为{pid_main}获取的包名为{package_name_main}")
                return None,None,None,None

        if len(CPDemo_processListdic)==2:
            do_log.info(f"2:获取到有效的进程号为2个,包名为{package_name}")
            try:
                package_name_main = CPDemo_processListdic[0]['pkgName']
                pid_main = CPDemo_processListdic[0]["PID"]
                user_main = CPDemo_processListdic[0]["USER"]
                for key in pid_list.keys():
                    if key in user_main:
                        pid_list[key]=pid_main
                        break
            except:
                do_log.info(f"2.尝试获取第1个有效进程号失败,包名为{package_name}")
                package_name_main,pid_main,user_main=None,None,None
            try:
                package_name_copilot = CPDemo_processListdic[1]['pkgName']
                pid_copilot=CPDemo_processListdic[1]["PID"]
                user_copilot = CPDemo_processListdic[1]["USER"]
                for key in pid_list.keys():
                    if key in user_copilot:
                        pid_list[key]=pid_copilot
                        break
            except:
                do_log.info(f"2.尝试获取第2个有效进程号失败,包名为{package_name}")
                package_name_copilot, pid_copilot,user_copilot = None, None,None

            if package_name_main == package_name and pid_main:
                do_log.info(f"2.尝试获取第1个有效进程号成功,获取的进程号为{pid_main}获取的包名为{package_name}")

                apm_pid_main = MyAppPerformanceMonitor(pkgName=self.pkgName, platform='Android',
                                                       deviceId=deviceId_001,
                                                       surfaceview=False,
                                                       noLog=False, pid=pid_main, record=False, collect_all=False)
            else:
                do_log.info(f"2.尝试获取第1个有效进程号失败,获取的进程号为{pid_main}获取的包名为{package_name_main}")
                apm_pid_main,pid_main=None,None
            if package_name_copilot == package_name and pid_copilot:
                do_log.info(f"2.尝试获取第2个有效进程号成功,获取的进程号为{pid_copilot}获取的包名为{package_name}")
                apm_pid_copilot = MyAppPerformanceMonitor(pkgName=self.pkgName, platform='Android',
                                                       deviceId=deviceId_001,
                                                       surfaceview=False,
                                                       noLog=False, pid=pid_copilot, record=False, collect_all=False)
            else:
                do_log.info(f"2.尝试获取第2个有效进程号失败,获取的进程号为{pid_copilot}获取的包名为{package_name_copilot}")
                apm_pid_copilot,pid_copilot=None,None

            return apm_pid_main,pid_main,apm_pid_copilot,pid_copilot




    def get_cpu(self, apm, cpu_num=None):
        if not cpu_num:
            cpu_num = 8
        result = apm.collectCpu()
        result["appCpuRate"] = result['appCpuRate'] * cpu_num
        result["systemCpuRate"] = result['systemCpuRate'] * cpu_num
        return result

    def get_mem(self, apm):
        return apm.collectMemory()['total']

    def get_sys_mem(self, apm):
        return apm.collectSysMemory()
    def get_fps(self, apm):
        return apm.collectFps()["fps"]
